import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, classification_report
from sklearn.model_selection import GridSearchCV

# 读取分类数据集
data = pd.read_csv("src\classification.csv")

# 删除有缺失的样本
data.dropna(inplace=True)

# 特征和标签
X = data.iloc[:, :-1]  # 特征
y = data.iloc[:, -1]   # 标签（分类）

# 划分数据集，80%训练，20%测试
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 参数设置：定义不同的C和gamma值
param_grid = {
    'C': [0.1, 1.0, 10.0],
    'gamma': [0.01, 0.1, 1],
    'kernel': ['rbf']  # 使用径向基函数核
}

# 使用GridSearchCV进行参数搜索
grid_search = GridSearchCV(SVC(), param_grid, cv=5)
grid_search.fit(X_train, y_train)

# 最佳参数
best_params = grid_search.best_params_
print(f"最佳参数: {best_params}")

# 使用最优参数训练SVM模型
best_model = grid_search.best_estimator_

# 预测测试集
y_pred = best_model.predict(X_test)

# 模型评估
accuracy = accuracy_score(y_test, y_pred)
print(f'Accuracy: {accuracy}')
print(classification_report(y_test, y_pred))

# 绘制混淆矩阵
from sklearn.metrics import ConfusionMatrixDisplay
ConfusionMatrixDisplay.from_estimator(best_model, X_test, y_test)
plt.title("Confusion Matrix")
plt.show()
